import 'package:flutter/material.dart';
import '../../services/database_helper.dart';
import 'article_detail.dart';
import 'package:flutter/services.dart'; 
import '../../services/tts_service.dart';

class PreviewArticlePage extends StatefulWidget {
  final int articleId;

  const PreviewArticlePage({
    Key? key,
    required this.articleId,
  }) : super(key: key);

  @override 
  State<PreviewArticlePage> createState() => _PreviewArticlePageState();
}

class _PreviewArticlePageState extends State<PreviewArticlePage> {
  Map<String, dynamic>? _article;
  bool _isLoading = true;
  int _progress = 61;
  final TTSService _tts = TTSService();
  bool _isSpeaking = false;
  int _currentWordIndex = -1;

  @override
  void initState() {
    super.initState();
    _loadArticleDetails();
    _initTTS();
  }

  Future<void> _initTTS() async {
    await _tts.init();
    _tts.setWordCallback((word, index) {
      print('Word callback at index: $index');
      setState(() {
        _currentWordIndex = index;
      });
    });
  }

  Future<void> _loadArticleDetails() async {
    try {
      await DatabaseHelper.init();
      final articles = await DatabaseHelper.getArticleById(widget.articleId);
      if (articles.isNotEmpty) {
        setState(() {
          _article = articles.first;
          _isLoading = false;
        });
      }
    } catch (e) {
      print('Error loading article details: $e');
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('文章预览'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
      ),
      body: Stack(
        children: [
          _isLoading
              ? const Center(child: CircularProgressIndicator())
              : SingleChildScrollView(
                  padding: const EdgeInsets.only(bottom: 80),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(20),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                  child: Text(
                                    _article?['title'] ?? '暂无内容',
                                    style: const TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                    ),
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 1,
                                  ),
                                ),
                                Stack(
                                  alignment: Alignment.center,
                                  children: [
                                    SizedBox(
                                      width: 50,
                                      height: 50,
                                      child: CircularProgressIndicator(
                                        value: _progress / 100,
                                        backgroundColor: Colors.grey[200],
                                        color: Colors.green,
                                      ),
                                    ),
                                    Text(
                                      '$_progress%',
                                      style: const TextStyle(
                                        fontSize: 14,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            const SizedBox(height: 8),
                            Row(
                              children: [
                                ...List.generate(5, (index) {
                                  // 根据 difficulty 决定星星是否点亮
                                  bool isActive = index < (_article?['difficulty'] ?? 0);
                                  return Padding(
                                    padding: const EdgeInsets.only(right: 4),
                                    child: Icon(
                                      Icons.star,
                                      size: 24,
                                      color: isActive ? Colors.amber : Colors.grey[300],
                                    ),
                                  );
                                }),
                                const SizedBox(width: 8),
                                
                              ],
                            ),
                            const SizedBox(height: 8),
                            Row(
                              children: [
                                const Icon(
                                  Icons.headphones,
                                  size: 20,
                                  color: Colors.grey,
                                ),
                                const SizedBox(width: 4),
                                Text(
                                  '支持音频播放',
                                  style: TextStyle(
                                    color: Colors.grey[600],
                                    fontSize: 14,
                                  ),
                                ),
                                const Spacer(),
                                IconButton(
                                  icon: Icon(
                                    _isSpeaking ? Icons.stop_circle : Icons.play_circle,
                                    color: const Color(0xFF4B6BFB),
                                    size: 28,
                                  ),
                                  onPressed: () async {
                                    if (_isSpeaking) {
                                      await _tts.stop();
                                    } else {
                                      await _tts.speak((_article?['content'] ?? '').toString());
                                    }
                                    setState(() {
                                      _isSpeaking = !_isSpeaking;
                                    });
                                  },
                                ),
                              ],
                            ),
                            const SizedBox(height: 24),
                            Text(
                              '文章预览',
                              style: TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.w500,
                                color: Colors.grey[800],
                              ),
                            ),
                            const SizedBox(height: 12),
                            RichText(
                              text: TextSpan(
                                children: (_article?['content'] ?? '暂无内容')
                                    .toString()
                                    .replaceAll('\\n', '\n')
                                    .split(RegExp(r'(?<=[\s,，.。!?！？、:：])|(?=[\s,，.。!?！？、:：])|\n'))
                                    .where((word) => word.isNotEmpty)
                                    .toList()
                                    .asMap()
                                    .entries
                                    .map((entry) {
                                      final index = entry.key;
                                      final word = entry.value;
                                      
                                      if (word == '\n') {
                                        return TextSpan(text: '\n');
                                      }
                                      
                                      final needsSpace = !RegExp(r'[,，.。!?！？、:：]$').hasMatch(word.trim());
                                      
                                      return TextSpan(
                                        text: word + (needsSpace ? ' ' : ''),
                                        style: TextStyle(
                                          fontSize: 14,
                                          height: 1.6,
                                          color: index == _currentWordIndex 
                                              ? const Color(0xFF4B6BFB)
                                              : Colors.grey[600],
                                          fontWeight: index == _currentWordIndex
                                              ? FontWeight.bold 
                                              : FontWeight.normal,
                                        ),
                                      );
                                    }).toList(),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 10,
                    offset: const Offset(0, -5),
                  ),
                ],
              ),
              child: ElevatedButton(
                onPressed: () async {
                  await HapticFeedback.heavyImpact();
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (_) => ArticleDetailPage(
                        articleId: widget.articleId,
                      ),
                    ),
                  );
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF4B6BFB),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  elevation: 2,
                  shadowColor: const Color(0xFF4B6BFB).withOpacity(0.5),
                ),
                child: const Text(
                  '立即学习',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          if (_isSpeaking) {
            await _tts.stop();
          } else {
            await _tts.speak(_article?['content'] ?? '');
          }
          setState(() {
            _isSpeaking = !_isSpeaking;
          });
        },
        child: Icon(_isSpeaking ? Icons.stop : Icons.volume_up),
      ),
    );
  }

  @override
  void dispose() {
    _tts.dispose();
    super.dispose();
  }
} 